// ==UserScript==
// @name           autohelp
// @namespace	http://userscripts.org/users/21452
// @description	automatically does jobs, boosts, & wars for the mafia wars facebook app. 
// @include	http://www.facebook.com/home.php?filter=app_10979261223&show_hidden=true
// @version	76
// ==/UserScript==

window.setTimeout(function (){
	var d = document.body.insertBefore(document.createElement('div'), document.body.firstChild )
	d.appendChild(document.createElement('script')).src = 'http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US'
	d.style.marginLeft = d.style.marginTop = "1em"
	d.appendChild(document.createElement('span')).innerHTML = ' <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=8335810">Donate now!</a><br />this script is supposed to delete the news feed items; it doesnt track which links it has visted between each refresh. it automatically unchecks the boxes when you hit the 25 limit, and checks again every 30 minutes. if betray is checked, it will pick a side for wars where both sides are friends, otherwise autohelp will skip the war'
	t = d.appendChild(document.createElement('table'))
	tr = t.appendChild(document.createElement('tr'))
	tr.innerHTML = '<th><a href="http://userscripts.org/scripts/show/57429">autohelp</a> version <span id="version">76</span></th><th>attempt</th><th>success</th><th>exp gain</th><th>percent</th>'
	exp = makeCheckbox('cuba', true)
	exp = exp.appendChild(document.createElement('td'))
	exp.id = 'AH_exp'
	exp.style.fontWeight = '1200'
	makeCheckbox('moscow', true)
	makeCheckbox('ny', true)
	makeCheckbox('boost', true)
	makeCheckbox('war', false)
	b = d.appendChild(document.createElement('button'))
	b.type = 'button'
	b.setAttribute('onclick', "tb = document.getElementsByTagName('table')[0].childNodes;for(i=1;i<tb.length;i++)tb[i].childNodes[2].textContent = tb[i].childNodes[1].textContent = tb[i].childNodes[3].textContent = 0;document.getElementById('AH_exp').textContent = 0")
	b.textContent = 'reset all counters'
	refreshTimer = d.appendChild(document.createElement('input'))
	refreshTimer.value = GM_getValue('refreshDelay', 2400)
	refreshTimer.id = 'AH_refreshDelay'
	refreshTimer.parentNode.appendChild(document.createElement('span')).textContent = '(ms) refresh delay.'
	b = d.appendChild(document.createElement('button'))
	b.id = 'AH_updateButton'
	b.textContent = 'check 4 updates'
	b.addEventListener('click', AH_updateCheck, false)
	function makeCheckbox(name, defaultval) {
		r = t.appendChild(document.createElement('tr'))
		r.id = name
		n = r.appendChild(document.createElement('td'))
		n.innerHTML = '<label><input type="checkbox" /> ' + name + '</label>'
		if (name == 'war') {
			n.innerHTML = n.innerHTML + '<label><input type="checkbox" id="AH_betray" /> betray</label>'
			n.getElementsByTagName('input')[1].checked = GM_getValue('betray', true)
		}
		r.appendChild(document.createElement('td')).textContent = GM_getValue(name +'Attempt', 0)
		r.appendChild(document.createElement('td')).textContent = GM_getValue(name +'Success', 0)
		r.appendChild(document.createElement('td')).textContent = GM_getValue(name +'Exp', 0)
		r.appendChild(document.createElement('td'))
		n.getElementsByTagName('input')[0].checked = GM_getValue(name, defaultval)
		return r
	}

	div = d.appendChild(document.createElement('div'))
	div.id = 'AH_log'
	d.appendChild(document.createElement('div')).innerHTML = '<fb:fan profile_id="159309131124" stream="1" connections="" width="230"></fb:fan>'
	
	window.setInterval(function(){
		document.getElementById('cuba').getElementsByTagName('input')[0] = true
		document.getElementById('ny').getElementsByTagName('input')[0] = true
		}, 1800000 )
	window.setInterval(function(){
		tb = document.getElementsByTagName('table')[0].children
		for( var i = 1; i < tb.length; i++ ) {
			n = tb[i].id
			GM_setValue(n + 'Attempt', parseInt(tb[i].childNodes[1].textContent))
			GM_setValue(n + 'Success', parseInt(tb[i].childNodes[2].textContent))
			GM_setValue(n + 'Exp', parseInt(tb[i].childNodes[3].textContent))
			GM_setValue(n, tb[i].getElementsByTagName('input')[0].checked)
			if (n == 'war')
				GM_setValue('betray', tb[i].getElementsByTagName('input')[1].checked)
		}
	}, 18000)
	window.setTimeout(function(){AH_go();window.location.href = 'javascript:void(FB.init("f0a3c663a5e9a052b7dafb5c0c399d67"))'}, 400)
	s = document.getElementById('home_sidebar')
	while(s.childNodes[1])
		s.removeChild(s.childNodes[1])
}, 3000)

function AH_updateCheck(){
	GM_xmlhttpRequest({method:'get', url:'http://userscripts.org/scripts/source/57429.meta.js', onload:function(r){
		s = r.responseText.toString()
		if( m = /@version\s+(\S+)/.exec(s) ){
			v = document.getElementById('version').textContent
			u = document.getElementById('AH_updateButton')
			if (m[1] == v)
				u.textContent = 'you have the latest version: ' + v
			else {
				u.textContent = 'update now! your version: ' + v + ' latest: ' + m[1]
				u.addEventListener( 'click', function(){
					u=document.getElementById('AH_updateButton')
					u.textContent = 'reload the page'
					u.addEventListener('click', function(){window.location.reload()
					window.location.href = 'http://userscripts.org/scripts/source/57429.user.js'}, false)
				}, false)
			}
		}
	} } )
}

function AH_go() {
	window.location = 'javascript:void(' + document.getElementsByClassName('UIIntentionalStream_ShowNewStories_Msg')[0].getAttribute('onclick') + ');'
	v = parseInt(document.getElementById('AH_refreshDelay').value)
	if(!v || v < 1100 || v > 22000)
		 v = 2400
	GM_setValue('refreshDelay', v)
	document.getElementById('AH_refreshDelay').value = v
	var p = document.getElementById('home_stream').getElementsByClassName('UIIntentionalStream_Content')[0]
	var c = 0
	tb = document.getElementsByTagName('table')[0].children
	for(i = 1; i < tb.length; i++){
		c += parseInt(tb[i].childNodes[3].textContent)
		num = tb[i].childNodes[1].textContent == '0' ? 100 : parseInt(tb[i].childNodes[2].textContent)*100.0/parseInt(tb[i].childNodes[1].textContent)
		tb[i].childNodes[4].textContent=(Math.round(num * 100) / 100) + '%'
	}
	document.getElementById('AH_exp').textContent = c + ' total exp'

	visted = {}
	while( d = p.firstChild ){
		var link = d.getElementsByTagName('a')
		while(l = link[0]) {
			if (URL = /(\/track\.php\?.*sendkey=(\w)+&.+)/.exec(l.href) ){
				k = URL[2]
				if (!visted[k]){
					URL = URL[1]
					if (m = /(requestjobhelpshort_cuba|give_help_m|give_help|boost_claim|story_war_helped|story_war_declared)/.exec(URL) ){
						var t
						switch( m[1] ) {
							case 'requestjobhelpshort_cuba': t = 1; break;
							case 'give_help_m': t = 2; break
							case 'give_help': t = 3; break
							case 'boost_claim': t = 4;break
							case 'story_war_helped' : case 'story_war_declared': t = 5
						}
						if(tb[t].getElementsByTagName('input')[0].checked ) {
							tb[t].childNodes[1].textContent = parseInt(tb[t].childNodes[1].textContent) + 1
							URL = 'http://mwfb.zynga.com/mwfb' + URL
							
	 						switch(t) {
								case 1: httpHelp(URL, function(s){httpHelp(s.split('top.location.href = "', 2)[1].split('"', 2)[0], function(s){job(s,1) } )});break
								case 2: httpHelp(URL, function(s){httpHelp(s.split('top.location.href = "', 2)[1].split('"', 2)[0], function(s){job(s,2) } )});break
								case 3: httpHelp(URL, function(s){httpHelp(s.split('top.location.href = "', 2)[1].split('"', 2)[0], function(s){job(s,3) } )});break
								case 4: httpHelp(URL, function(s){httpHelp(s.split('top.location.href = "', 2)[1].split('"', 2)[0], boost )});break
								case 5: httpHelp(URL, function(s){httpHelp(s.split('top.location.href = "', 2)[1].split('"', 2)[0], war )});break
							}
						}
					}
					visted[k] = true
				}
			}
			l.parentNode.removeChild(l)
		}
		p.removeChild(d)
	}
	window.setTimeout(AH_go, v)
}

function job(s, r){
	row = document.getElementsByTagName('table')[0].children[r]
	if (q = /<span class="good">(\d+) experience points<\/span>/.exec(s) ) {
		row.childNodes[3].textContent = parseInt(row.childNodes[3].textContent) + parseInt(q[1])
		row.childNodes[2].textContent = parseInt(row.childNodes[2].textContent) + 1
	}
	else if( /Sorry, you can only help 25 friends/.test(s) )
		row.getElementsByTagName('input')[0].checked = false
}

function boost(s){ if( m = /You received an? (.*?) from/.exec(s) ){
	success = document.getElementById('boost').children[2]
	success.textContent = parseInt(success.textContent) + 1
	l = document.getElementById('AH_log')
	l.textContent = l.textContent + ' ' + m[1]
	}
}

function war(s){
	function attack(s, n) {
		if (n > 5) return true
		var end = s.lastIndexOf('<span class="sexy_fight">Attack</span>')
		if (end == -1) return false
		start = s.lastIndexOf('href="http://apps.facebook.com/inthemafia/remote/html_server.php?', end)
		end = s.indexOf('"',start + 8)
		httpHelp(  s.substring(start + 6, end).replace(/&amp;/g, '&'), function(s){
			if(/WON|LOST/.test(s)) {
				war = document.getElementById('war').children
				war[3].textContent = parseInt(war[3].textContent) + 3
				war[2].textContent = parseInt(war[2].textContent) + 1
			}
			else
				attack(s, n+1)
		} )
		return true
	}
	if( !attack(s, 0) ) {
		var end = s.lastIndexOf( '<span class="sexy_fight">Betray')
		if (end == -1 || !document.getElementById('war').getElementsByTagName('input')[1].checked) return
		start = s.lastIndexOf('href="http://apps.facebook.com/inthemafia/remote/html_server.php?', end)
		end = s.indexOf('"',start + 8)
		httpHelp( 'http://apps.facebook.com/inthemafia/index.php?'  + s.substring(start + 65, end).replace(/&amp;/g, '&'), attack)
	}
}

function httpHelp(u, func, n){
	GM_xmlhttpRequest({method:'get', url:u, onload:function(r){
			if (n == undefined) n = 0
			else if (n > 5) return
			s = r.responseText.toString()
			if (!s) httpHelp(u, func, n + 1)
			else func(s)
		}
	})
}